import json
import os
from typing import Dict, List, Any

def extract_non_motor_vehicle_attributes(data: Dict[str, Any]) -> List[Dict[str, Any]]:
    """
    从JSON数据中提取非机动车属性标注信息
    
    Args:
        data: 包含非机动车检测结果的JSON数据
    
    Returns:
        符合COCO格式的非机动车标注列表
    """
    # 车身颜色映射表（中文 -> 数值）
    color_mapping = {
        "白色车身": 0,
        "橙色车身": 1,
        "棕色车身": 2,
        "花色车身": 3,
        "灰色车身": 4,
        "黑色车身": 5,
        "绿色车身": 6,
        "蓝色车身": 7,
        "红色车身": 8,
        "紫色车身": 9,
        "黄色车身": 10,
        "粉色车身": 11
    }
    
    # 车型映射表（中文 -> 数值）
    vehicle_type_mapping = {
        "摩托车/电瓶车": 1,
        "自行车": 2,
        "三轮车(封闭驾驶舱)": 3,
        "三轮车(有篷)": 4,
        "三轮车(无篷&无封闭)": 5
    }
    
    annotations = []
    
    # 获取图像信息
    image_data = data.get("Result", {}).get("Image", {}).get("Data", {})
    image_id = image_data.get("Id", "")
    image_width = image_data.get("Width", 0)
    image_height = image_data.get("Height", 0)
    
    # 处理每个非机动车
    for vehicle in data.get("Result", {}).get("NonMotorVehicles", []):
        # 获取基础信息
        vehicle_id = vehicle.get("Id", 0)
        bbox = vehicle.get("Img", {}).get("DetectedBox", {})
        
        # 提取属性
        motor_body_color = -1  # 默认值-1表示未知
        vehicle_type = -1      # 默认值-1表示未知
        
        for attr in vehicle.get("Attributes", []):
            attr_name = attr.get("Name", "")
            if attr_name == "车身颜色":
                color_str = attr.get("ValueString", "")
                motor_body_color = color_mapping.get(color_str, -1)
            
            elif attr_name == "车型":
                type_str = attr.get("ValueString", "")
                vehicle_type = vehicle_type_mapping.get(type_str, -1)
        
        # 构建COCO格式的标注
        annotation = {
            "id": f"3{vehicle_id:03d}",  # 非机动车ID格式: 3开头 + 3位数字
            "image_id": image_id,
            "category_id": 3,  # 非机动车类别ID
            "sub_category": vehicle_type,
            "bbox": [
                bbox.get("X", 0),
                bbox.get("Y", 0),
                bbox.get("Width", 0),
                bbox.get("Height", 0)
            ],
            "attributes": {
                "motor_body_color": motor_body_color
            },
            "is_crowd": 0,  # 默认单辆车
            "child_id": [],  # 关联人体ID列表
            "track_id": vehicle.get("UId", "")  # 轨迹ID
        }
        
        annotations.append(annotation)
    
    return annotations, image_id, image_width, image_height

def generate_coco_annotation(input_file: str):
    """
    生成完整的COCO格式标注并保存到文件
    
    Args:
        input_file: 输入JSON文件名
    """
    try:
        # 检查输入文件是否存在
        if not os.path.exists(input_file):
            raise FileNotFoundError(f"输入文件 {input_file} 不存在")
        
        # 生成输出文件名（在输入文件名前加"coco_"）
        base_name = os.path.basename(input_file)
        output_file = os.path.join(
            os.path.dirname(input_file),
            f"coco_{base_name}"
        )
        
        # 加载原始JSON数据
        with open(input_file, "r", encoding="utf-8") as f:
            original_data = json.load(f)
        
        # 提取非机动车标注和图像信息
        annotations, image_id, img_width, img_height = extract_non_motor_vehicle_attributes(original_data)
        
        # 创建COCO格式数据结构
        coco_data = {
            "info": {
                "description": "Non-motor Vehicle Annotation",
                "version": "1.0",
                "date_created": "2023-11-15"
            },
            "licenses": [],
            "images": [{
                "id": image_id,
                "width": img_width,
                "height": img_height,
                "file_name": f"{image_id}.jpg"  # 假设文件名基于图像ID
            }],
            "annotations": annotations,
            "categories": [{
                "id": 3,
                "name": "Non_motor_veichle",
                "supercategory": "vehicle"
            }]
        }
        
        # 保存结果
        with open(output_file, "w", encoding="utf-8") as f:
            json.dump(coco_data, f, ensure_ascii=False, indent=2)
        
        print(f"成功生成COCO标注文件: {output_file}")
        print(f"包含 {len(annotations)} 个非机动车标注")
        return output_file
        
    except FileNotFoundError as e:
        print(f"错误: {str(e)}")
    except json.JSONDecodeError:
        print(f"错误: 文件 {input_file} 不是有效的JSON格式")
    except Exception as e:
        print(f"处理过程中发生错误: {str(e)}")
    return None
def print_file_lines(filename):
    """
    打印文件的每一行内容，并移除行尾的换行符
    
    参数:
        filename (str): 要读取的文件路径
    """
    try:
        with open(filename, 'r') as file:
            for line in file:
                # 移除行尾的换行符和回车符
                clean_line = line.rstrip('\n\r')
                generate_coco_annotation(clean_line)
                print(clean_line)
    except FileNotFoundError:
        print(f"错误：文件 '{filename}' 不存在")
    except Exception as e:
        print(f"读取文件时出错: {str(e)}")

# 示例使用
if __name__ == "__main__":
    # 示例调用 - 只需要一个输入文件参数
    # input_filename = "keyframe_0001.json"
    # output_file = generate_coco_annotation(input_filename)
    print_file_lines("list1")
